//
//  AppDelegate.m
//  jiyujiaProgram
//
//  Created by 中良 赵 on 15/10/13.
//  Copyright (c) 2015年 中良 赵. All rights reserved.
//

#import "AppDelegate.h"
#import "TabBarViewController.h"
#import "ECDefine.h"
#import "LoginViewController.h"
#import "ApplyViewController.h"

#import "IQKeyboardManager.h"

#pragma mark - 环信KEY

/*
 应用标识(AppKey):	jikei2015#riyujia
 创建时间:	2015-09-30 13:45:36
 最后修改时间:	2015-09-30 13:45:36
 用户注册模式:	开放注册            切换
 当前注册用户总数:	0
 Client Id:	YXA6eT0-4Gc2EeWYKPE7peOhfg
 Client Secret:	YXA6r4mUTUkijRfO3GGfXAJ3gHAR0pQ
 */

extern "C"{
    size_t fwrite$UNIX2003( const void *a, size_t b, size_t c, FILE *d )
    {
        return fwrite(a, b, c, d);
    }
    char* strerror$UNIX2003( int errnum )
    {
        return strerror(errnum);
    }
}

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    _connectionState = eEMConnectionConnected;
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];

    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginStateChange:)
                                                 name:KNOTIFICATION_LOGINCHANGE
                                               object:nil];

    
    [[EaseMob sharedInstance].chatManager setIsAutoFetchBuddyList:YES];
    [[EaseMob sharedInstance] registerSDKWithAppKey:@"jikei2015#riyujia" apnsCertName:@""];
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    [[EaseMob sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    [self setupNotifiers];
    
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = NO;


    [self loginStateChange:nil];
    [self.window makeKeyAndVisible];
    return YES;
}


#pragma mark ------ NOTIFIERS------
- (void)setupNotifiers{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidEnterBackgroundNotif:)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillEnterForeground:)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidFinishLaunching:)
                                                 name:UIApplicationDidFinishLaunchingNotification
                                               object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidBecomeActiveNotif:)
                                                 name:UIApplicationDidBecomeActiveNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillResignActiveNotif:)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appDidReceiveMemoryWarning:)
                                                 name:UIApplicationDidReceiveMemoryWarningNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appWillTerminateNotif:)
                                                 name:UIApplicationWillTerminateNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appProtectedDataWillBecomeUnavailableNotif:)
                                                 name:UIApplicationProtectedDataWillBecomeUnavailable
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appProtectedDataDidBecomeAvailableNotif:)
                                                 name:UIApplicationProtectedDataDidBecomeAvailable
                                               object:nil];
}

#pragma mark - notifiers
- (void)appDidEnterBackgroundNotif:(NSNotification*)notif{
    [[EaseMob sharedInstance] applicationDidEnterBackground:notif.object];
}

- (void)appWillEnterForeground:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationWillEnterForeground:notif.object];
}

- (void)appDidFinishLaunching:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationDidFinishLaunching:notif.object];
}

- (void)appDidBecomeActiveNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationDidBecomeActive:notif.object];
}

- (void)appWillResignActiveNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationWillResignActive:notif.object];
}

- (void)appDidReceiveMemoryWarning:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationDidReceiveMemoryWarning:notif.object];
}

- (void)appWillTerminateNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationWillTerminate:notif.object];
}

- (void)appProtectedDataWillBecomeUnavailableNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationProtectedDataWillBecomeUnavailable:notif.object];
}

- (void)appProtectedDataDidBecomeAvailableNotif:(NSNotification*)notif
{
    [[EaseMob sharedInstance] applicationProtectedDataDidBecomeAvailable:notif.object];
}



#pragma mark ---------loginStateChange----------
-(void)loginStateChange:(NSNotification *)notification
{
    UserInfoManager *userInfo = [UserInfoManager sharedUserInfoManager];
    [userInfo loadUserInfoFromSanbox];
    MemberModel *model = userInfo.memberModel;
    BOOL isAutoLogin = [[EaseMob sharedInstance].chatManager isAutoLoginEnabled];

    [[EaseMob sharedInstance].chatManager importDataToNewDatabase];
    //获取数据库中数据
    [[EaseMob sharedInstance].chatManager loadDataFromDatabase];
    //获取群组列表
    [[EaseMob sharedInstance].chatManager asyncFetchMyGroupsList];

    if ([model.member_type integerValue] == 2&&userInfo.autoLogin&&isAutoLogin) {
        _mainTabBarVC = [[MainTabViewController alloc] init];
        UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:_mainTabBarVC];
        self.window.rootViewController = navc;
        navc.navigationBarHidden = YES;
    }else if([model.member_type integerValue] == 1&&userInfo.autoLogin&&isAutoLogin){
        TabBarViewController *tabBar = [[TabBarViewController alloc] init];
        self.window.rootViewController = tabBar;
        self.window.backgroundColor = ECCOLOR(255, 255, 255, 1);
    }else{
        LoginViewController *vc=[[LoginViewController alloc]init];
        UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:vc];
        self.window.rootViewController=navc;
        navc.navigationBarHidden=YES;
    }
}

// 将要开始自动登录
-(void)willAutoLoginWithInfo:(NSDictionary *)loginInfo
                       error:(EMError *)error{
    if (!error) {
        NSLog(@"开始自动登录%@",loginInfo);
    }else{
        NSLog(@"开始自动登录失败%@",error);
    }
}
// 自动登录结束
-(void)didAutoLoginWithInfo:(NSDictionary *)loginInfo
                      error:(EMError *)error{
    if (!error) {
        NSLog(@"自动登录成功%@",loginInfo);
    }else{
        NSLog(@"自动登录失败%@",error);
    }
}


- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [[EaseMob sharedInstance] applicationDidEnterBackground:application];
}

// App将要从后台返回
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [[EaseMob sharedInstance] applicationWillEnterForeground:application];
}

// 申请处理时间
- (void)applicationWillTerminate:(UIApplication *)application
{
    [[EaseMob sharedInstance] applicationWillTerminate:application];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


@end
